package com.doudou.base.resources.util;


import com.doudou.client.entity.AppClientDetailsDto;
import com.doudou.commons.utils.ListUtils;
import com.google.gson.Gson;
import io.swagger.annotations.ApiModelProperty;
import javolution.util.FastSet;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 傻男人
 * @date 2020-05-08 22:09
 * @describe
 */
public class ClientDetailsUtil {
    /**
     * 客户端重定向uri
     */
    @ApiModelProperty("客户端重定向uri")
    private String webServerRedirectUri;
    /**
     * 指定用户的权限范围
     */
    @ApiModelProperty("指定用户的权限范围")
    private String authorities;


    public static ClientDetails loadClientByAppInfo(AppClientDetailsDto appClientDetailsDto) {
        BaseClientDetails bcd = new BaseClientDetails();
        bcd.setClientId(appClientDetailsDto.getClientId());
        bcd.setAuthorities(Arrays.asList("ISV_CORP").stream().map(role -> new SimpleGrantedAuthority(role)).collect(Collectors.toList()));
        bcd.setResourceIds(ListUtils.strToStringList(appClientDetailsDto.getResourceIds()));
        bcd.setScope(ListUtils.strToStringList(appClientDetailsDto.getScope()));
        bcd.setClientSecret(appClientDetailsDto.getClientSecret());
        bcd.setAdditionalInformation(new Gson().fromJson(appClientDetailsDto.getAdditionalInformation(), Map.class));
        bcd.setAuthorizedGrantTypes(ListUtils.strToStringList(appClientDetailsDto.getAuthorizedGrantTypes()));
        bcd.setAccessTokenValiditySeconds(appClientDetailsDto.getAccessTokenValidity());
        bcd.setRefreshTokenValiditySeconds(appClientDetailsDto.getRefreshTokenValidity());
        bcd.setAutoApproveScopes(ListUtils.strToStringList(appClientDetailsDto.getAutoapprove()));
        Set<String> set = FastSet.newInstance();
        set.addAll(ListUtils.strToStringList(appClientDetailsDto.getWebServerRedirectUri()));
        bcd.setRegisteredRedirectUri(set);
        return bcd;
    }



}
